<?php

namespace App;


use App\Utils\Os;
use Noodlehaus\Config;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Wonfu\Core\AbstractApplication;
use Wonfu\Core\AppConfig;



class Application extends AbstractApplication
{



    public function boot(AppConfig $appConfig)
    {
        $this->allowCors();
        date_default_timezone_set('Asia/Shanghai');
        $this->appConfig = $appConfig;
        $this->tmpClear();
        $options = ['gc_maxlifetime' => 3600 * 12];
        $sessionHandler = new SessionHandler($options);
        $redis = $this->container->get(\RedisCluster::class);
        $sessionHandler->setClient($redis);
        $sessionHandler->register();
        // 自定义sessionId
        ini_set('session.name', 'MALLPANELTOKEN');
        if (empty($_COOKIE[session_name()])) {
            session_id(session_create_id('mall-panel-'));
        }
        session_start();
        $exceptionHandler = new ExceptionHandler();
        $this->exceptionHandler = $exceptionHandler;
//        $this->container->injectOn($exceptionHandler);
        set_exception_handler([$exceptionHandler, 'dispatch']);
        // since php7+ set_exception_handler 也能捕获error,因此set_error_handler可能用不到
        error_reporting(-1);
        set_error_handler([new ErrorHandler(),'dispatch']);
        return $this;
    }

    /**
     * 自动删除aop的缓存文件，手动更新下app配置的info.version
     * @throws \DI\DependencyException
     * @throws \DI\NotFoundException
     * @throws \Psr\Cache\InvalidArgumentException
     */
    private function tmpClear()
    {
        $config = $this->container->get(Config::class);
        $version = $config->get('info.version');
        $cache = new FilesystemAdapter();
        $oldVersionItem = $cache->getItem('api.version');
        if ($version != $oldVersionItem->get()) {
            Os::batchUnlink(TMP_DIR,'*.php');
            $oldVersionItem->set($version);
            $cache->save($oldVersionItem);
        }

    }


    private function allowCors()
    {
        if(!headers_sent()){
            //存在 Authorization 的header ,简单的Access-Control-Allow-Origin 设置不能解决跨域问题
            header('Access-Control-Allow-Origin: *');
            header('Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');
            header('Access-Control-Expose-Headers: Authorization');
            header('Access-Control-Allow-Methods: DELETE, GET, HEAD, POST, PUT, OPTIONS, TRACE, PATCH');
        }
    }

}